package com.leyou.gateway.filters;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: YHL
 * @time: 2021/3/8 18:23
 */
@Component
public class UserLoginFilter implements GlobalFilter {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            //任务，判断是否登录，如果登录了，重置过期时间，否则，直接放行
            HttpCookie cookie = exchange.getRequest().getCookies().toSingleValueMap().get("LY_TOKEN");


            if (cookie == null) {
                //放行
                return chain.filter(exchange);
            }

            String token = cookie.getValue();

            Payload payload = this.jwtUtils.parseJwt(token);

            String key = "ly:token:user:"+payload.getUserDetail().getId();


            //重置过期时间
            this.redisTemplate.expire(key,30, TimeUnit.MINUTES);
        } catch (Exception e) {
            //放行
            return chain.filter(exchange);
        }


        //放行
        return chain.filter(exchange);

    }
}
